<template>
    <div class="job">
        <button @click="getJob">向后端请求数据</button>
        <button @click="is_showJob">新增职位</button>
        <div class="updateJob" v-if="showInsertJob">
            职位名称：<input type="text" v-model="jobName">
            <button @click="saveInsertJob">保存</button>
        </div>
        <table class="Job">
            <caption class="title">职位表</caption>
            <thead>
                <tr>
                    <th>id</th>
                    <th>职位</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="item in JobArr" :key="item.id">
                    <td>{{ item.id }}</td>
                    <td>
                        {{ item.name }}
                        <div class="JobUpdate" v-if="showJob&&item.id==indexJob">
                            <input type="text" v-model="updateJob">
                            <button @click="saveUpdateJob(item.id)" >保存</button>
                        </div>
                        
                    </td>
                    <td>
                        <button @click="delJob(item.id)">删除</button>
                        <button @click="isShowUpdateJob(item.id)">修改</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>
<script lang="ts" setup name="Job">
import axios from 'axios';
import { onMounted, ref } from 'vue';
interface JobData {
    id: number,
    name: string
}
onMounted(()=>{
    getJob();
})
let JobArr=ref<JobData[]>([]);
async function getJob(){
    let {data}=await axios.get("http://localhost:8080/jobs");
    JobArr.value=data.data;
}
async function saveInsertJob(){
    
    let {data}=await axios.post("http://localhost:8080/jobs",{
        name: jobName.value
    })
    getJob();
    showInsertJob.value=false;
}
let showInsertJob=ref(false);
function is_showJob(){
    showInsertJob.value=true;
}
async function saveUpdateJob(id:number){

let {data} =await axios.put("http://localhost:8080/jobs",{
    id: id,
    name: updateJob.value
})

getJob();
showJob.value=false;
}
let jobName=ref("");
async function delJob(id:number){
    let data=await axios.delete("http://localhost:8080/jobs/"+id);
    
    getJob();
    alert("删除职位成功");
}
let showJob=ref(false);
let updateJob=ref("");
let indexJob=ref(-1);
function isShowUpdateJob(index: number){
    showJob.value=true;
    indexJob.value=index;
}
</script>
<style scoped>
.job{
    border: 2px solid black;
    margin-bottom: 100px;
}
.Job{
     
     width: 100%;  
     border-collapse: collapse;  
    
    th, td {  
        border: 1px solid #000000;  
        padding: 8px;  
        text-align: center;
    }  
}
</style>